package com.bwf.lgqingdan.mvp.presenter.impl;

import com.bwf.lgqingdan.entity.ResponseArticles;
import com.bwf.lgqingdan.mvp.model.ArticleListModel;
import com.bwf.lgqingdan.mvp.model.impl.ArticleListModelImpl;
import com.bwf.lgqingdan.mvp.presenter.ArticleListPresenter;
import com.bwf.lgqingdan.mvp.view.ArticleListView;
import com.bwf.lgqingdan.utils.Apis;
import com.bwf.lgqingdan.utils.UrlHandler;

/**
 * Created by Administrator on 2016/11/18.
 */

public class ArticleListPresenterImpl implements ArticleListPresenter, ArticleListModel.Callback {
    private ArticleListModel model;
    private ArticleListView view;
    private int categoryId;
    private int nextPage;
    public static final int TAG_DEFAULT = 0;
    public static final int TAG_NEWEST = 1;
    public static final int TAG_HOTTEST = 2;
    private int tag;
    public ArticleListPresenterImpl(int categoryId,ArticleListView view) {
        this.view = view;
        this.model = new ArticleListModelImpl();
        this.categoryId = categoryId;
        nextPage = 1;
    }


    @Override
    public void loadInitArticles() {
        nextPage = 1;
        loadNextPageArticlesSortByDefault();
    }

    @Override
    public void loadNextPageArticlesSortByDefault() {
        if(tag != TAG_DEFAULT){
            nextPage = 1;
        }
        String url = UrlHandler.handlUrl(Apis.API_TAG_ARTICLES_SORT_BY_DEFAULT,categoryId,nextPage);
        model.loadArticles(url,this);
    }

    @Override
    public void loadNextPageArticlesSortByNewest() {
        if(tag != TAG_NEWEST){
            nextPage = 1;
        }
        String url = UrlHandler.handlUrl(Apis.API_TAG_ARTICLES_SORT_BY_NEWEST,categoryId,nextPage);
        model.loadArticles(url,this);
    }

    @Override
    public void loadNextPageArticlesSortByHottest() {
        if(tag != TAG_HOTTEST){
            nextPage = 1;
        }
        String url = UrlHandler.handlUrl(Apis.API_TAG_ARTICLES_SORT_BY_HOTTEST,categoryId,nextPage);
        model.loadArticles(url,this);
    }

    @Override
    public void loadNextPageArticles() {
        switch (tag){
            case TAG_DEFAULT:
                loadNextPageArticlesSortByDefault();
                break;
            case TAG_HOTTEST:
                loadNextPageArticlesSortByHottest();
                break;
            case TAG_NEWEST:
                loadNextPageArticlesSortByNewest();
                break;
        }
    }

    @Override
    public void loadArticlesSuccess(ResponseArticles responseArticles) {
        if(responseArticles.getData().getMeta().getPagination().getCurrent_page()
                == responseArticles.getData().getMeta().getPagination().getTotal_pages()){
            view.showNoMoreArticles();
        }
        view.showLoadArticlesSuccess(nextPage,responseArticles.getData().getArticles());
        nextPage++;
    }

    @Override
    public void loadArticlesFailed(String failedMsg) {
        view.showLoadArticlesFailed(failedMsg);
    }
}
